# -*- coding: utf-8 -*-
# 版权所有 (c) [王广旭]，本程序创作于[2025年1月19号]
# 本程序由王广旭开发，保留所有权利。
# 严禁将本程序以任何形式用于商业用途。
# 非商业使用需遵循以下条件：
# - 不得删除或修改此版权声明。
# - 若对程序进行再分发，需包含此版权声明。

import os
from time import sleep

from common.utils.common_functions import exit_program, current_time_to_str
from common.utils.excel_read import ExcelRead
from common.utils.keywords import Keywords
from common.utils.licensee import Licensee


if __name__ == "__main__":
    print("""
# 版权所有 (c) [王广旭]，本程序创作于[2025年1月19号]
# 本程序由王广旭开发，保留所有权利。
# 严禁将本程序以任何形式用于商业用途。
# 非商业使用需遵循以下条件：
# - 不得删除或修改此版权声明。
# - 若对程序进行再分发，需包含此版权声明。
    """)

    licensee = Licensee()

    if not os.path.exists("logs"):
        os.makedirs("logs")
    log_path = f"logs/{current_time_to_str()}_app_test_adb.log"
    keywords = Keywords()
    excel_read = ExcelRead()

    click_interval = 0
    try:
        click_interval = int(excel_read.click_interval)
        if click_interval <= 100:
            print("等待时间至少100ms")
            click_interval = 100
    except ValueError:
        exit_program(f"{excel_read.test_case_file_path}表2第{excel_read.row_click_interval_pos + 1}行的"
                     f"{excel_read.row_click_interval_title}参数无效，请重新填写")

    for device_identifier in excel_read.device_identifier_list:
        if licensee.is_provide_demo:
            print("adb connect {}".format(device_identifier))
            if not keywords.is_connect_device(device_identifier):
                print(f"请检查设备{device_identifier}是否存在")
                print("退出程序，演示不退出")
        else:
            keywords.connect_device(device_identifier)
            if not keywords.is_connect_device(device_identifier):
                exit_program(f"请检查设备{device_identifier}是否存在")

    test_loop_index = 0
    use_case_number = len(excel_read.use_case_datas)
    for test_data in excel_read.use_case_datas:
        step = test_data[excel_read.col_step_pos]
        if len(step) >= 3 and step[:3] == "初始化":

            if test_data[excel_read.col_key_word_pos] == "sleep":
                try:
                    test_time = int(test_data[excel_read.col_test_data_pos]) * 1000
                    wait_time = click_interval - test_time
                    if wait_time < 0:
                        wait_time = 0
                    sleep(wait_time / 1000.0)
                except ValueError:
                    exit_program(f"{excel_read.test_case_file_path}表1第{test_loop_index + 1}行"
                                 f"等待时间数据{test_data[excel_read.col_test_data_pos]}无效，请重新填写")

            f = getattr(keywords, "app_{}".format(test_data[excel_read.col_key_word_pos]))
            if excel_read.col_device_identifier_pos == -1:
                f(test_data[excel_read.col_test_data_pos:], excel_read.device_identifier)
            else:
                f(test_data[excel_read.col_test_data_pos:], test_data(excel_read.col_device_identifier_pos))
            test_loop_index += 1
            log = f"{current_time_to_str()}  {step}"
            print(log)
            with open(log_path, 'a', encoding='utf-8') as file:
                file.write("{}\n".format(log))
            sleep(click_interval / 1000.0)
        else:
            break

    while True:
        start_pos = test_loop_index
        try:
            while start_pos < use_case_number:
                test_data = excel_read.use_case_datas[start_pos]
                step = test_data[excel_read.col_step_pos]

                if test_data[excel_read.col_key_word_pos] == "sleep":
                    wait_time = 0
                    try:
                        test_time = int(test_data[excel_read.col_test_data_pos]) * 1000
                        wait_time = click_interval - test_time
                        if wait_time < 0:
                            wait_time = 0
                        sleep(wait_time / 1000.0)
                    except ValueError:
                        exit_program(f"{excel_read.test_case_file_path}表1第{test_loop_index + 1}行"
                                     f"等待时间数据{test_data[excel_read.col_test_data_pos]}无效，请重新填写")
                f = getattr(keywords, "app_{}".format(test_data[excel_read.col_key_word_pos]))
                if excel_read.col_device_identifier_pos == -1:
                    f(test_data[excel_read.col_test_data_pos:], excel_read.device_identifier)
                else:
                    f(test_data[excel_read.col_test_data_pos:], test_data(excel_read.col_device_identifier_pos))
                start_pos += 1
                log = f"{current_time_to_str()}  {step}"
                print(log)
                with open(log_path, 'a', encoding='utf-8') as file:
                    file.write("{}\n".format(log))
                sleep(click_interval / 1000.0)
        except:
            exit_program("")



